import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:seedfour/app/models/income_invoice_entity.dart';

import '../../../models/api_response/list_data_entity.dart';
import '../../../models/case_list_entity.dart';
import '../../../models/income_order_list_entity.dart';
import '../../../models/org_name_entity.dart';
import '../../../models/payees_entity.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class OrderIncomeCreateLogic extends GetxController {
  late GlobalKey<FormState> formKey;

  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  // 付款账户输入框控制器
  final TextEditingController accountText = TextEditingController();

  // 收款金额输入框控制器
  final TextEditingController amountText = TextEditingController();

  // 订单备注输入框控制器
  final TextEditingController orderRemarkText = TextEditingController();

  // 电子邮箱输入框控制器
  final TextEditingController emailText = TextEditingController();

  // 发票抬头输入框控制器
  final TextEditingController titleText = TextEditingController();

  // 纳税人识别号输入框控制器
  final TextEditingController taxpayerCodeText = TextEditingController();

  // 货物或应税劳务名称
  final TextEditingController businessText = TextEditingController();

  // 公司地址输入框控制器
  final TextEditingController companyAddressText = TextEditingController();

  // 公司电话输入框控制器
  final TextEditingController companyPhoneText = TextEditingController();

  // 银行账号输入框控制器
  final TextEditingController bankAccountText = TextEditingController();

  // 开户银行输入框控制器
  final TextEditingController bankNameText = TextEditingController();

  // 发票备注输入框控制器
  final TextEditingController invoiceRemarkText = TextEditingController();

  final payeesName = ''.obs;
  final payeesItemName = ''.obs;
  final settlementOptions = <PayeesItemsOptions>[].obs;
  final attachmentName = ''.obs;
  final isShowAttachment = false.obs;
  final caseList = <CaseInfo?>[].obs;
  final selectedCaseIndies = <int>[].obs;
  final selectedCases = <CaseInfo?>[].obs;

  final selectedFiles = <PlatformFile>[].obs;
  final invoiceAttachs = <IncomeInvoiceOrderAttach>[].obs;

  final isInvoice = false.obs;
  final selectedInvoiceType = Rxn<String>();
  final settlementValue = Rxn<PayeesItemsOptions>();

  final isCreate = true.obs;
  final orderDetail = Rxn<IncomeOrderInfo>();
  final invoiceDetail = Rxn<IncomeInvoiceEntity>();

  var orgNames = <String>[].obs;

  final Map<String, String> invoiceType = {
    'onlineArc': '电子普票',
    'offlineArc': '电子专票',
  };

  @override
  void onInit() {
    super.onInit();
    formKey = GlobalKey<FormState>();

    orderDetail.value = Get.arguments;

    if (orderDetail.value != null) {
      isCreate.value = false;
      isInvoice.value = true;

      invoiceDetail.value = IncomeInvoiceEntity.fromJson(
          jsonDecode(orderDetail.value!.invoice ?? ''));

      if (invoiceDetail.value!.showTab != null &&
          invoiceDetail.value!.showTab! != '') {
        selectedInvoiceType.value = invoiceDetail.value!.showTab!;
      }

      accountText.text = orderDetail.value!.title ?? '';

      amountText.text = orderDetail.value!.orderAmount.toString();
      orderRemarkText.text = orderDetail.value!.remark ?? '';

      emailText.text = invoiceDetail.value!.email ?? '';
      titleText.text = invoiceDetail.value!.title ?? '';
      taxpayerCodeText.text = invoiceDetail.value!.taxid ?? '';
      businessText.text = invoiceDetail.value!.cargo ?? '';
      companyAddressText.text = invoiceDetail.value!.address ?? '';
      companyPhoneText.text = invoiceDetail.value!.phone ?? '';
      bankAccountText.text = invoiceDetail.value!.bankacct ?? '';
      bankNameText.text = invoiceDetail.value!.bankname ?? '';
      invoiceRemarkText.text = invoiceDetail.value!.remark ?? '';
    } else {
      isCreate.value = true;
      invoiceDetail.value = IncomeInvoiceEntity();
      invoiceDetail.value!.relateCases = [];
      invoiceDetail.value!.orderAttachs = [];

      _getSettlementOptions();
      _getCaseList();
    }
  }

  // 选中案件
  void onSelectedCase(int index) {
    if (selectedCaseIndies.contains(index)) {
      selectedCaseIndies.remove(index);
    } else {
      selectedCaseIndies.add(index);
    }
  }

  // 确认选中案件
  void onConfirmSelectedCase() {
    selectedCases.clear();
    selectedCases.addAll(selectedCaseIndies.map((index) => caseList[index]));
  }

  // 取消选中案件
  void onCanceledSelectedCase() {
    selectedCaseIndies.clear();
  }

  void onCreateCase() {
    Get.toNamed(RouteGet.caseCreate, arguments: true);
  }

  // 选择结算方式
  void setSelectedInvoiceType(String type) {
    selectedInvoiceType.value = type;
  }

  // 选择文件
  void pickFile() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    );
    if (result != null) {
      isShowAttachment.value = true;
      selectedFiles.addAll(result.files
          .where((file) => !selectedFiles.any((s) => s.path == file.path)));
    }
  }

  // 删除文件
  void deleteFile(int index) {
    selectedFiles.removeAt(index);
  }

  // 从pdf网络地址下载pdf文件
  void downloadFile() async {
    String urlPath =
        'https://www.seedfour.com/sfres/pages/%E4%BA%91%E5%98%89%E5%BE%8B%E6%89%80%E4%BB%A3%E4%BB%98%E8%AF%B4%E6%98%8E%E6%A8%A1%E6%9D%BF20250114.pdf';
    EasyLoading.show(status: '附件下载中...');

    Directory? appDocDir = await getDownloadsDirectory();
    String savePath = '${appDocDir!.path}/云嘉律所代付说明模板20250114.pdf';

    final response = await Dio().download(urlPath, savePath);

    if (response.statusCode == 200) {
      EasyLoading.showToast('文件已保存到: $savePath',
          duration: const Duration(seconds: 6));
    } else {
      EasyLoading.showToast(
        '文件下载失败',
      );
    }
  }

  void getCompanyInfo(String name, TextEditingController codeController) {
    if(name.isEmpty) {
      return;
    }

    apiService.getCompanyInfo(name).then((value) {
      if (value != null) {
        codeController.text = value.value['data']['nsrsbh'];
      }
    });
  }

  Future<List<String>> searchOrg(String name) async {
    if (name.isEmpty) {
      return [];
    }
    ListDataEntity<OrgNameEntity>? result = await apiService.searchOrg(name);
    if (result != null) {
      orgNames.clear();
      orgNames.addAll(result.data!.map((e) => e.name!).toList());
      return orgNames;
    }
    return [];
  }

  void submit() async {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();

      EasyLoading.show(status: '创建中...');
      final result = await _uploadFile();

      if (!result) {
        EasyLoading.dismiss();
        EasyLoading.showError('上传文件失败');
        return;
      }

      _createOrder();
    }
  }

  void _getSettlementOptions() {
    String mobile = commonService.getUser().mobile!;

    apiService.getPayees(mobile).then((value) {
      if (value != null) {
        payeesName.value = value.name ?? '';
        payeesItemName.value = value.items![0].name ?? '';
        settlementOptions.value = value.items![0].options
            .where((o) => o.settleRatio != null)
            .toList();
      }
    });
  }

  void _getCaseList() {
    apiService
        .listAllCase(commonService.getRole(), 'selectCase')
        .then((caseList) {
      if (caseList != null) {
        this.caseList.addAll(caseList.all!);
      }
    });
  }

  Future<bool> _uploadFile() async {
    if (selectedFiles.isEmpty) {
      return true;
    }

    for (var file in selectedFiles) {
      final result = await apiService.uploadFile(file.path!);
      if (result != null) {
        invoiceAttachs.add(IncomeInvoiceOrderAttach(
          name: result.name,
          url: result.tempPath,
        ));
      } else {
        return false;
      }
    }

    return true;
  }

  void _createOrder() async {
    invoiceDetail.value!.cargo =
        businessText.text.isEmpty ? '服务费' : businessText.text;
    invoiceDetail.value!.showTab =
        isInvoice.value ? selectedInvoiceType.value : '';
    invoiceDetail.value!.relateCases?.addAll(selectedCases
        .map((caseInfo) => IncomeInvoiceRelateCases(
              caseId: caseInfo?.id,
              caseName: caseInfo?.caseNameStr,
            ))
        .toList());

    invoiceDetail.value!.taxid = taxpayerCodeText.text;
    invoiceDetail.value!.address = companyAddressText.text;
    invoiceDetail.value!.bankacct = bankAccountText.text;
    invoiceDetail.value!.bankname = bankNameText.text;
    invoiceDetail.value!.phone = companyPhoneText.text;
    invoiceDetail.value!.email = emailText.text;
    invoiceDetail.value!.title = titleText.text;

    if (invoiceAttachs.isNotEmpty) {
      invoiceDetail.value!.orderAttachs!.addAll(invoiceAttachs);
    }

    final result = await apiService.createIncomeOrder(
        orderId: orderDetail.value == null ? '' : orderDetail.value!.id,
        amount: amountText.text,
        invoice: invoiceDetail.value!.toString(),
        mobile: commonService.getUser().mobile!,
        settleRatio: settlementValue.value == null
            ? 0
            : settlementValue.value!.settleRatio ?? 0,
        title: accountText.text);

    if (result != null) {
      EasyLoading.dismiss();

      if (isCreate.value) {
        EasyLoading.showSuccess('创建成功');
        Get.back(result: true);
      } else {
        EasyLoading.showSuccess('修改成功');
        Get.back(result: invoiceDetail.value);
      }
    }
  }

  @override
  void onClose() {
    accountText.dispose();
    amountText.dispose();
    orderRemarkText.dispose();
    emailText.dispose();
    taxpayerCodeText.dispose();
    businessText.dispose();
    companyAddressText.dispose();
    companyPhoneText.dispose();
    bankAccountText.dispose();
    bankNameText.dispose();
    invoiceRemarkText.dispose();
    super.onClose();
  }
}
